<?php
namespace App\Lib\Mongodb;

use EasySwoole\EasySwoole\Trigger;
use MongoDB\Client;
use MongoDB\Database;

class MongodbDriver
{
    private $_client;
    private $_config;

    // 【建议使用】
    // 使用 mongodb/mongodb composer组件包封装的 MongoDB 客户端调用类，作为客户端调用驱动
    // 【前提：需要先使用 `composer require mongodb/mongodb` 安装 mongodb/mongodb composer组件包】
    public function __construct($config)
    {
        // 这里为要连接的 mongodb 的服务端地址【前提是必须先有服务端，且安装 php-mongodb 扩展才可使用】
        $mongoServer = "mongodb://";
        if ($config['username']) {
            $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
        }
        $mongoServer .= $config['hostname'];
        if ($config['port']) {
            $mongoServer .= ':' . $config['port'] . '/' . $config['database'];
        }
        $this->_config = $config;
        $this->_client = new Client($mongoServer);


    }
    public function getDb(): Database
    {
        return new Database($this->getClient()->getManager(), $this->_config['database']);
    }
    public function getClient(): Client {
        return $this->_client;
    }
    public function getMongodbDriver(): MongodbDriver
    {
        return $this;
    }

    protected function onException(\Throwable $throwable)
    {
        Trigger::getInstance()->throwable($throwable);
        return null;
    }
}